#include	"a_global_vars.h"

int	ipmulti_send	(int sock, inst *i_msg, int msg_size,  struct sockaddr_in* addr);
//------------------------------------------------------------------------------
int create_ip_multicast_sender_socket(const char *ip){
	
	struct ip_mreq multi;
	int ipm_sid = socket(AF_INET, SOCK_DGRAM,0);
	assert(ipm_sid >= 0);
	
	multi.imr_multiaddr.s_addr=inet_addr(ip);
	return ipm_sid;
}
//------------------------------------------------------------------------------
int create_ip_multicast_receiver_socket(int port, const char *ip, const char *ip2){
	
	struct sockaddr_in ipm_addr;
	struct ip_mreq mreq;
	int activate = 1, status;
	
	int ipm_sid = socket(AF_INET,SOCK_DGRAM,0);
	assert(ipm_sid >= 0 );
	status = setsockopt(ipm_sid, SOL_SOCKET, SO_REUSEADDR, &activate, sizeof(int));
	assert(status == 0);
	
	ipm_addr.sin_family	=	AF_INET;
	ipm_addr.sin_addr.s_addr	=	inet_addr(ip);// u can change ip to INADDR_ANY
	ipm_addr.sin_port	=	htons(port);
	
	status = bind(ipm_sid,(struct sockaddr*) &ipm_addr, sizeof(ipm_addr));
	assert(status >= 0 );

	mreq.imr_multiaddr.s_addr	=	inet_addr(ip);
	mreq.imr_interface.s_addr	=	inet_addr(ip2);//INADDR_ANY;//;//;this uses the default NIC on the system. 
	
	status = setsockopt(ipm_sid, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
	assert(status >= 0);
	
	int flag = fcntl(ipm_sid, F_GETFL);
	assert(flag >= 0 );
    flag |= O_NONBLOCK;
	status = fcntl(ipm_sid, F_SETFL, flag);
	assert(status >= 0);
	
	return ipm_sid;
}
//------------------------------------------------------------------------------
struct sockaddr_in getAddr(int port, const char *ip){
	
	struct sockaddr_in address;
	memset(&address, '\0', sizeof(struct sockaddr_in));
	
	address.sin_family	=	AF_INET;
	address.sin_addr.s_addr	=	inet_addr(ip);
	address.sin_port	=	htons(port);
	
	return address;
}
//------------------------------------------------------------------------------
int ipmulti_send(int sock, inst *i_msg, int msg_size,  struct sockaddr_in* addr){
    int cnt = -1;
    cnt = sendto(sock, i_msg, msg_size, MSG_WAITALL, (struct sockaddr *)addr, sizeof(struct sockaddr_in));
    return cnt;
}


